package org.example.halfsearch;

public class Half {
    /**
     * 二分搜索（一个数最左值下标）
     * */
    public int halfsearch(int []arr,int i){
        int tempindex=-1;
        int left = 0;
        int right = arr.length-1;
        int middle = 2;
        while(left<right&&middle>1){
            middle=left+(right-left)/2;
            if(arr[middle]>i){
                right = middle-1;
            }
            else if (arr[middle]<i){
                left = middle+1;
            }
            else{
                tempindex = middle;
                right = tempindex;
            }
        }
        return  tempindex;
    }
    /**
     * 扩展（二分搜索局部最小）
     * */
    public int mini(int []arr){
        int left = 0;
        int right = arr.length-1;
        int middle = 2;
        int tempindex = -1;
        while (left<=right&&middle>1){
            middle = (right-left)/2;
            if(arr[middle-1]>arr[middle]){
                right =middle-1;

            }
            else if(arr[middle+1]>arr[middle]){
                left=middle+1;
            }
            else{
                break;
            }

        }
        return arr[middle];
    }
}
